package com.qipay.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import okhttp3.*;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class RC4 {

    public static String decry_RC4(byte[] data, String key) {
        if (data == null || key == null) {
            return null;
        }
        return asString(RC4Base(data, key));
    }

    public static String decry_RC4(String data, String key) {
        if (data == null || key == null) {
            return null;
        }
        return new String(RC4Base(HexString2Bytes(data), key));
    }

    public static byte[] encry_RC4_byte(String data, String key) {
        if (data == null || key == null) {
            return null;
        }
        byte b_data[] = data.getBytes();
        return RC4Base(b_data, key);
    }

    public static String encry_RC4_string(String data, String key) {
        if (data == null || key == null) {
            return null;
        }
        return toHexString(asString(encry_RC4_byte(data, key)));
    }

    private static String asString(byte[] buf) {
        StringBuffer strbuf = new StringBuffer(buf.length);
        for (int i = 0; i < buf.length; i++) {
            strbuf.append((char) buf[i]);
        }
        return strbuf.toString();
    }

    private static byte[] initKey(String aKey) {
        byte[] b_key = aKey.getBytes();
        byte state[] = new byte[256];

        for (int i = 0; i < 256; i++) {
            state[i] = (byte) i;
        }
        int index1 = 0;
        int index2 = 0;
        if (b_key == null || b_key.length == 0) {
            return null;
        }
        for (int i = 0; i < 256; i++) {
            index2 = ((b_key[index1] & 0xff) + (state[i] & 0xff) + index2) & 0xff;
            byte tmp = state[i];
            state[i] = state[index2];
            state[index2] = tmp;
            index1 = (index1 + 1) % b_key.length;
        }
        return state;
    }

    private static String toHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = (int) s.charAt(i);
            String s4 = Integer.toHexString(ch & 0xFF);
            if (s4.length() == 1) {
                s4 = '0' + s4;
            }
            str = str + s4;
        }
        return str;// 0x表示十六进制
    }

    private static byte[] HexString2Bytes(String src) {
        int size = src.length();
        byte[] ret = new byte[size / 2];
        byte[] tmp = src.getBytes();
        for (int i = 0; i < size / 2; i++) {
            ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
        }
        return ret;
    }

    private static byte uniteBytes(byte src0, byte src1) {
        char _b0 = (char) Byte.decode("0x" + new String(new byte[]{src0})).byteValue();
        _b0 = (char) (_b0 << 4);
        char _b1 = (char) Byte.decode("0x" + new String(new byte[]{src1})).byteValue();
        byte ret = (byte) (_b0 ^ _b1);
        return ret;
    }

    private static byte[] RC4Base(byte[] input, String mKkey) {
        int x = 0;
        int y = 0;
        byte key[] = initKey(mKkey);
        int xorIndex;
        byte[] result = new byte[input.length];

        for (int i = 0; i < input.length; i++) {
            x = (x + 1) & 0xff;
            y = ((key[x] & 0xff) + y) & 0xff;
            byte tmp = key[x];
            key[x] = key[y];
            key[y] = tmp;
            xorIndex = ((key[x] & 0xff) + (key[y] & 0xff)) & 0xff;
            result[i] = (byte) (input[i] ^ key[xorIndex]);
        }
        return result;
    }

    private static int thread_num = 30;
    private static int client_num = 10000;

    //自动获取参数
    public static void main(String[] args) throws IOException, InterruptedException {
        String mall_id="890040476";
        String pddUid = "2326825162875";
        String PDDAccessToken="KMGRT3QQADHCIY27H3JLEI3L7OWD67MOVPU6IJ53TISSHFQC7SGA1007b21";


        OkHttpClient client = new OkHttpClient();
        String money = "";
        String goods_id = "";
        String sku_id = "";
        String group_id = "";

        Request request2 = new Request.Builder()
                .url("http://mobile.yangkeduo.com/proxy/api/api/turing/mall/query_mall_promotion_goods?mall_id="+mall_id+"&refer_page_param=&offset=0&count=20&pdduid=" + pddUid)
                .get()
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0")
                .addHeader("Accept", "*/*")
                .addHeader("Cache-Control", "no-cache")
                .addHeader("cookie", "PDDAccessToken="+PDDAccessToken)
                .addHeader("Host", "mobile.yangkeduo.com")
                .addHeader("Connection", "keep-alive")
                .addHeader("cache-control", "no-cache")
                .build();

        Response response2 = client.newCall(request2).execute();
        String list = response2.body().string();
        JSONObject jsonObject = JSONObject.parseObject(list);
        JSONArray goodsList = JSONObject.parseArray(jsonObject.getString("goods_list"));

        String[] goodIds = new String[goodsList.size()];
        int[] moneys = new int[goodsList.size()];
        String[] groupIds = new String[goodsList.size()];
        String[] skuIds = new String[goodsList.size()];
        for (int i = 0; i < goodsList.size(); i++) {
            JSONObject js = JSONObject.parseObject(goodsList.get(i).toString());
            goodIds[i] = js.getString("goods_id");
            moneys[i] = new BigDecimal(js.getIntValue("customer_price")).divide(new BigDecimal("100"), 0, BigDecimal.ROUND_DOWN).intValue();
        }

        for (int i = 0; i < goodIds.length; i++) {
            Request request = new Request.Builder()
                    .url("http://mobile.yangkeduo.com/goods.html?goods_id=" + goodIds[i] + "&is_spike=0&refer_page_name=mall&refer_page_id=10039_1557992090681_fTM5inMrSn&refer_page_sn=10039")
                    .get()
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0")
                    .addHeader("Accept", "*/*")
                    .addHeader("Cache-Control", "no-cache")
                    .addHeader("Host", "mobile.yangkeduo.com")
                    .addHeader("cookie", "PDDAccessToken="+PDDAccessToken)
                    .addHeader("Connection", "keep-alive")
                    .addHeader("cache-control", "no-cache")
                    .build();

            Response response = client.newCall(request).execute();
            String body = response.body().string();
            if (body.indexOf("\"skus\":[{\"skuID\":") != -1) {
                String skuId = body.substring(body.lastIndexOf("\"skus\":[{\"skuID\":") + 17, body.lastIndexOf("\"skus\":[{\"skuID\":") + 29);
                skuIds[i] = skuId;
                String groupID = body.substring(body.lastIndexOf("\"requireNum\":\"1\",\"price\":\"0\",\"totalPrice\":\"0\",\"groupID\":") + 56, body.lastIndexOf("\"requireNum\":\"1\",\"price\":\"0\",\"totalPrice\":\"0\",\"groupID\":") + 67);
                groupIds[i] = groupID;
            }
        }

        //外部循环
        for (int i = 0; i < moneys.length - 1; i++) {
            //相连两个数的索引是利用内部循环
            for (int index = 0; index < moneys.length - 1; index++) {
                //同样利用中间变量，注意区分与选择排序的区分
                if (moneys[index] > moneys[index + 1]) {
                    int temp = moneys[index];
                    moneys[index] = moneys[index + 1];
                    moneys[index + 1] = temp;
                    String goodId = goodIds[index];
                    goodIds[index] = goodIds[index + 1];
                    goodIds[index + 1] = goodId;
                    String groupId = groupIds[index];
                    groupIds[index] = groupIds[index + 1];
                    groupIds[index + 1] = groupId;
                    String skuId = skuIds[index];
                    skuIds[index] = skuIds[index + 1];
                    skuIds[index + 1] = skuId;
                }
            }
        }
        for (int i = 0; i < moneys.length; i++) {
            if (moneys[i]%100==0) {
                goods_id += goodIds[i] + "/";
                group_id += groupIds[i] + "/";
                sku_id += skuIds[i] + "/";
                money += moneys[i] + "/";
            }
        }
        System.out.println("goods_id:" + goods_id.substring(0, goods_id.length() - 1));
        System.out.println("group_id:" + group_id.substring(0, group_id.length() - 1));
        System.out.println("money:" + money.substring(0, money.length() - 1));
        System.out.println("sku_id:" + sku_id.substring(0, sku_id.length() - 1));
    }
//    public static void main(String[] args) throws IOException, InterruptedException {
//        //创建缓冲线程池，用于执行多线程
//        ExecutorService exec = exec = Executors.newFixedThreadPool(150);
//        //thread_num个线程可以同时访问
//        final Semaphore semp = new Semaphore(thread_num);
//        String[] orderList = "190718-561592730671447".split(",");
//        System.out.println(orderList.length);
////        String [] moneyList="10000,10000,80000,30000,20000,20000,20000,80000,10000,100000,10000,10000,20000,20000,10000,30000,20000,10000,10000,30000,300000,20000,200000,100000,50000,20000,10000,100000,10000,10000,30000,10000,100000,200000,40000,10000,10000,50000,20000,20000,30000,100000,200000,100000,50000,10000,10000,20000,100000,10000,20000,10000,30000,10000,10000,100000,10000,10000,10000,30000,10000,10000,50000,20000,30000,20000,10000,100000,10000,50000,10000,10000,10000,20000,10000,50000,20000,50000,10000,10000,200000,30000,10000,30000,10000,10000,10000,20000,100000,10000,50000,10000,10000,10000,100000,30000,20000,10000,10000,10000,100000,10000,100000,10000,10000,30000,100000,80000,30000,10000,20000,20000,10000,10000,50000,20000,200000,50000,30000,30000,10000,100000,10000,20000,20000,10000,20000,10000,20000,20000,50000,50000,10000,20000,100000,10000,20000,20000,10000,20000,10000,30000,10000,20000,50000,10000,10000,20000,10000,300000,20000,300000,20000,10000,10000,10000,10000,10000,10000,10000,300000,20000,50000,10000,50000,10000,10000,50000,10000,20000,50000,10000,10000,30000,200000,50000,20000,10000,10000,20000,50000,10000,100000,30000,10000,10000,10000,20000,10000,10000,10000,10000,10000,300000,20000,100000,30000,10000,300000,100000,10000,10000,20000,30000,50000,300000,10000,20000,20000,50000,20000,10000,200000,10000,20000,20000,10000,50000,10000,30000,10000,30000,80000,20000,10000,30000,10000,10000,30000,20000,50000,40000,10000,10000,50000,10000,10000,10000,20000,30000,30000,20000,10000,10000,10000,50000,10000,10000,100000,20000,10000,10000,20000,10000,20000,100000,10000,50000,30000,10000,50000,10000,10000,200000,100000,100000".split(",");
//        String[] pdduid = "5976823301543/7556828481064/8726828913179".split("/");
//        String[] AccessToken = "3J7KBFYN4AA6BGM25KGLXVA44QYONB3HP6B32YZBDNSGIUS5OYKQ101a75a/ROLRIASVFJH2LQAZLTLO47XITTURRSD24GND4D2AVT3ESDOBDNVQ1022883/YTGA2SX56QJ2OGOZNXMJGXL4BB3ZPFPN2D2CT7FZNSVIP2UKMVPA1021b03".split("/");
////        String [] pdduid="9576513389173/9176514527538/5236519519884/5256512918474/5556517932049/1956514054523/9106512502056/1306515782169/4426516333305/7326511575001/4076517311319/7306511770667/4866510290438/8566511462724/9216517330802/6726510969233".split("/");
////        String [] AccessToken="TAEYPJDPHSRACUB6Q424WLNK2CNK5FMHDCG3HKRBDDBN7QN2HXVA1027521/VCJO76JYY6RV2WXZXGTYIDZY2JXL73DKFLKQHBEHSS4U45AKSL3Q1013243/DTOD2EZSC3NBMMYRNK2UBOBLDC3D26UAFSLR2G7NCUCUHQ3XFLVA1028c7d/IUVSOOBQJERQH4YZFNPW2IC4AQUEYJGS22MOEHAHOFQVQQBQVM2Q103ca37/LDOYOGUFQS7O3KIHAO2F6NANZXV566OX6CSN3TEPW26WYVVWR3KA1001170/Y7KECHPSTQVJKJV55WVQFLA7M4BIYKQ6RX54L7PPKEBH5SBLXDBA1017b28/AGEYFHP3CZEFSJSPIGO3XHJDJ4Y2IOZMPSJP5EWX2FWVXKNWTP7Q101280d/MDLG7WJCCD7NTTQNP6QBAIYCSUWVZZ7W6DNIWLWJZZHZROLG2JBA102196d/ULLV2NOH2TSJZBJT24BX5NJZPPMDT5MJRGWPJNDEG4TAUZGEODNQ102f9ae/LFRG6ZV2HN6NFNKR2TWLE7FQV6HH56QZ3DXAGPS6BPQV2FSN6T3A103d951/YTAO57VGJP57BTZB7PTMHAYALMNZJN3VVUBT3ABPRTVXTRJ6ZHDA1035785/IRBVNUW2EXSBMNIZQ56HZ7TLJFZ67SDKMEFB33FO4BBGAGE5S22Q1002b12/SONJDDSZGQYSTBHN36DM6OXUGLUABW2365RIFOUZGWBWFRQJ7AUQ1020612/3TCVR2GHAKNVZR66QZYHCYO6VGOYQISAQGSRKO7SEBPEWG2ZLZSA1014413/5OBPN7CJV2RG7RCKNZYMFWBLEAYLZB5O6ZPP3NDLDQJMOSF7C33Q103722b/6WLG4BPUOVAAH5C7QPKQNX5Q5KA637IQG7LVHICD2UBKCUKPMG6Q101915c".split("/");
////        String [] pdduid="5907703234519/3337813715849/5257819419376/9477814494551/3745493773/7633445629/3952682533/3795730656".split("/");
////        String [] AccessToken="KNTII4C5644LB36J5D7ID3M2WPFALLEDKARTCGVCB2MRZ2IFQKJQ103d72e/W3QXZLNQSCUNJ7REJQUNTE6NR5AIMWTT6ORFGBAYECMG2Q3RM6YQ103895e/UQEF2M5DO4AVCNXOUO3Z6PJK6FPWSVWGAXKMMFVPAF4RGXFE6JFA102f058/L5Q2BJE4IOGXPRVJJCWLPGBLIX3X27UQMX5PONRCCKL6SG76BCEA1015742/ONK6YAOWJ7TFAUSL3ASNJPIN4VSP2RJT3K7ESVVQAHVKLABEU6QQ1030d95/UV66M2YR522GA75OIUM7EVM4UKKLVVWGQ7TJ2YI3LDITQVCDO4UQ102fd34/BTKIOPWZ6MJBNCDTXF5QXU4QJJAHJSIENPATQUSRU6OBPRDI3LOQ102253b/O4IHQDU55IQFYTBKWGF3QQNQ6E52FPSCDV32ARQV2PVQXW2IAOSQ100e04f".split("/");
////        String [] pdduid="17048962394/17048962401/17048962402".split("/");
////        String [] AccessToken="UZFZIEJ5RE5MKELKCB6JMZVRINIURMC5LPC3C6KK2AS2U7KVGY3A100b321/WRAIETKRBLLKC3M6476KYWLVT3EUGIOEIJPFVIHUUG7BJ3TTOGRA103065d/RIUS2UNPZ3YNESQ4XBSLZPA7EPX3DZRJ7HXDF5L7E5CBHOTDHQAQ102d3ba".split("/");
//        for (int i = 0; i < orderList.length; i++) {
//            final int NO = i;
//            //run方法内是线程执行的内容
//            for (int j = 0; j < pdduid.length; j++) {
//                final int NO2 = j;
//                Runnable run = new Runnable() {
//                    public void run() {
//                        try {
//                            // 获取许可
//                            semp.acquire();
//                            //手动补单
////                    OkHttpClient client = new OkHttpClient();
////
////                    MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
////                    RequestBody body = RequestBody.create(mediaType, "orderno="+orderList[NO]+"&price="+moneyList[NO]);
////                    Request request = new Request.Builder()
////                            .url("http://106.52.242.102:8100/api/callback/v1/pdd/wx")
////                            .post(body)
////                            .addHeader("Content-Type", "application/x-www-form-urlencoded")
////                            .addHeader("Accept", "*/*")
////                            .addHeader("Cache-Control", "no-cache")
////                            .addHeader("Host", "106.52.242.102:8100")
////                            .addHeader("cache-control", "no-cache")
////                            .build();
////
////                    Response response = client.newCall(request).execute();
//                            //手动签单
//                            OkHttpClient client = new OkHttpClient();
//
//                            MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
//                            RequestBody body = RequestBody.create(mediaType, "pdduid=" + pdduid[NO2]);
//                            Request request = new Request.Builder()
//                                    .url("http://mobile.yangkeduo.com/proxy/api/order/" + orderList[NO] + "/received")
//                                    .post(body)
//                                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
//                                    .addHeader("AccessToken", AccessToken[NO2])
//                                    .addHeader("Accept", "*/*")
//                                    .addHeader("Cache-Control", "no-cache")
//                                    .addHeader("Host", "mobile.yangkeduo.com")
//                                    .addHeader("Connection", "keep-alive")
//                                    .addHeader("cache-control", "no-cache")
//                                    .build();
//
//                            Response response = client.newCall(request).execute();
//                            String result = response.body().string();
//                            if (!result.contains("60002")) {
//                                System.out.println("第" + NO + "个orderList[i]:" + orderList[NO] + "/pdduid[NO2]:" + pdduid[NO2] + "/" + result);
//                            }
//                            // 释放许可
//                            semp.release();
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                };
//                //执行线程
//                exec.execute(run);
//            }
//            Thread.sleep(1000);
//        }
//        Thread.sleep(1000);
//    }
//    public static void main(String[] args) throws IOException, InterruptedException {
//        OkHttpClient client = new OkHttpClient();
//
//        Request request = new Request.Builder()
//                .url("https://qnf.gznxbank.com/ifsp-payweb/merUnionPayReceive?qrCode=https%3a%2f%2fqr.95516.com%2f00010002%2f62012799077899978469268165430781")
//                .get()
//                .addHeader("Content-Type", "application/x-www-form-urlencoded")
//                .addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16E227 NebulaSDK/1.8.100112 Nebula WK PSDType(1) AlipayDefined(nt:WIFI,ws:375|603|2.0) AliApp(AP/10.1.62.6001) AlipayClient/10.1.62.6001 Alipay Language/zh-Hans")
//                .addHeader("Accept", "*/*")
//                .addHeader("Cache-Control", "no-cache")
//                .addHeader("Postman-Token", "22fa9840-09d2-41f1-9da3-8b4e19adec98,9a39c6f5-582a-42f6-b746-6478922e63cc")
//                .addHeader("referer", "https://qnf.gznxbank.com/ifsp-payweb/merUnionPayReceive?qrCode=https%3A%2F%2Fqr.95516.com%2F00010002%2F62012799077899978469268165430781")
//                .addHeader("Connection", "keep-alive")
//                .addHeader("cache-control", "no-cache")
//                .build();
//
//        Response response = client.newCall(request).execute();
//
//        String j=response.request().url().toString();
//
//        System.out.println(j);
//        j=j.substring(49,81);
//        OkHttpClient client2 = new OkHttpClient();
//
//        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
//        RequestBody body = RequestBody.create(mediaType, "amt=0.01&paySessionCode="+j);
//        Request request2 = new Request.Builder()
//                .url("https://qnf.gznxbank.com/ifsp-payweb/merOneCodePay")
//                .post(body)
//                .addHeader("Content-Type", "application/x-www-form-urlencoded")
//                .addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/16E227 NebulaSDK/1.8.100112 Nebula WK PSDType(1) AlipayDefined(nt:WIFI,ws:375|603|2.0) AliApp(AP/10.1.62.6001) AlipayClient/10.1.62.6001 Alipay Language/zh-Hans")
//                .addHeader("Accept", "*/*")
//                .addHeader("Cache-Control", "no-cache")
//                .addHeader("Postman-Token", "c5a74390-7ba8-431e-ac6d-6b6ba876da3c,3de61654-c897-457a-ae8d-b2f42a615e61")
//                .addHeader("Host", "qnf.gznxbank.com")
//                .addHeader("content-length", "")
//                .addHeader("Connection", "keep-alive")
//                .addHeader("cache-control", "no-cache")
//                .build();
//
//        Response response2 = client.newCall(request2).execute();
//        String bodystr=response2.body().string();
//         System.out.println(bodystr);
//        JSONObject jsonObject = JSONObject.parseObject(bodystr);
//        String urlStr=jsonObject.getString("codeUrl");
//        System.out.println(urlStr);
//    }
}